package com.syq.play.ui;


import java.io.IOException;

import com.syq.play.AppContent;
import com.syq.play.R;
import com.syq.play.model.MediaModel;
import com.syq.play.service.IPlayer;
import com.syq.play.service.LocalService;
import com.syq.play.util.MyStringUtil;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources.Theme;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

public class SRPlayActivity extends ActivityGroup implements OnClickListener{
	private static final String TAG="SRPlayActivity";
	public static final String ACTION_PREV_NEXT="actionPrevNext";
	public static SRPlayActivity mActivityGroup = null;
	private LocalActivityManager mLocalActivityManager = null;
	private Context context;
	private LinearLayout container;
	private ImageView ivIcon;
	private ToggleButton tbPlay;
	private TextView tvMusicName, tvMusicArtist, tvTime;
	public IPlayer mPlayer;
	private ServiceConnection mConnection = new ServiceConnection() { 
	    public void onServiceConnected(ComponentName className, IBinder service) { 
	        mPlayer = IPlayer.Stub.asInterface(service);
	    } 
	    public void onServiceDisconnected(ComponentName className) { 

	    }; 
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        mActivityGroup=this;
        mLocalActivityManager=getLocalActivityManager();
        context=this;
        container=(LinearLayout)findViewById(R.id.ll_container);
        ivIcon=(ImageView)findViewById(R.id.iv_icon);
        mStartActivity(IndexActivity.class, null);
        initUi();
        initListener();
        bindService(new Intent(context,  
                LocalService.class), mConnection, Context.BIND_AUTO_CREATE); 
        startService(new Intent(context,  
                LocalService.class)); 
        mThread.start();
    }
    private void initUi(){
    	tvTime=(TextView)findViewById(R.id.tv_time);
    	tbPlay=(ToggleButton)findViewById(R.id.tb_play);
    	tvMusicName=(TextView)findViewById(R.id.tv_music_name);
    	tvMusicArtist=(TextView)findViewById(R.id.tv_music_artist);
    	tbPlay.setChecked(false);
    }
    private void initListener(){
    	findViewById(R.id.bt_prev).setOnClickListener(this);
    	findViewById(R.id.bt_next).setOnClickListener(this);
    	ivIcon.setOnClickListener(this);
    	findViewById(R.id.ll_name).setOnClickListener(this);
    	tbPlay.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				play(isChecked);
			}
		});
    }
	/** 
     * 根据ID打开指定的Activity 
     * @param id GridView选中项的序号 
     */  
   public void mStartActivity(Class activityClass, Bundle data){  
        container.removeAllViews();//必须先清除容器中所有的View  
        Intent intent = new Intent(context, activityClass);  
        if(data!=null && !data.isEmpty()){
        	intent.putExtras(data);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
        //Activity 转为 View  
        Window subActivity = getLocalActivityManager().startActivity(  
                "subActivity", intent);  
        //容器添加View  
        container.addView(subActivity.getDecorView(),  
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 
    }  
   @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if(keyCode==KeyEvent.KEYCODE_BACK){
			 Activity activiyt=mLocalActivityManager.getCurrentActivity();
			 activiyt.onKeyDown(keyCode, event);
			 return false;
		 }
		return super.onKeyDown(keyCode, event);
	}
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.bt_prev:
			toPrev();
			break;
		case R.id.bt_next:
			toNext();
			break;
		case R.id.iv_icon:
		case R.id.ll_name:
			Intent intent=new Intent(context, PlayActivity.class);
			intent.putExtra("title", ""+tvMusicName.getText());
			startActivity(intent);
			break;
		}
	}
	public void playMusic( int position){
		if(mPlayer!=null){
			try {
				mPlayer.setPlayPosition(position);
				mPlayer.play();
				tbPlay.setChecked(true);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
	private void play(boolean isChecked){
		if(isChecked){
			try {
				mPlayer.play();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}else{
			try {
				mPlayer.pause();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}
	private void toPrev(){
		try {
			if(mPlayer!=null && mPlayer.isPrepare()){
				mPlayer.playPre();
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	private void toNext(){
		try {
			if(mPlayer!=null && mPlayer.isPrepare()){
				mPlayer.playNext();
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	private Thread mThread=new Thread(){
		public void run() {
			try {
				for(;;){
					mHandler.sendMessage(new Message());
					Thread.sleep(1000);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		};
	};
	private Handler mHandler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			try {
				if(mPlayer!=null && mPlayer.isPrepare()){
					tbPlay.setClickable(true);
					tvMusicName.setText(""+mPlayer.getTitle());
					tvMusicArtist.setText(""+mPlayer.getArtist());
					long cTime=(long)mPlayer.getCurrentTime();
					long DTime=(long)mPlayer.getDuration();
					tvTime.setText(MyStringUtil.formatLongToTimeStr(cTime)+"/"+MyStringUtil.formatLongToTimeStr(DTime));
					if(mPlayer.isPlaying()){
						tbPlay.setChecked(true);
					}else{
						tbPlay.setChecked(false);
					}
				}else{
					tbPlay.setClickable(false);
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	};
//	private void setTitleAndArtist(){
//        try {
//			if(mPlayer!=null && mPlayer.isPrepare()){
//				tvMusicName.setText(""+mPlayer.getTitle());
//				tvMusicArtist.setText(""+mPlayer.getArtist());
//			}
//		} catch (RemoteException e) {
//			e.printStackTrace();
//		}
//	}
}